package org.onvivals.admin.module.iot.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.common.param.PageParam;
import org.onvivals.common.web.PageResult;
import org.onvivals.common.web.Result;
import org.onvivals.module.iot.entity.IotDevice;
import org.onvivals.module.iot.param.IotDeviceParam;
import org.onvivals.module.iot.service.IIotDeviceService;
import org.onvivals.module.pms.entity.PmsRole;
import org.onvivals.module.pms.service.IPmsRoleService;
import org.onvivals.module.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * IotDeviceController
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "设备")
@RequestMapping("/device")
public class IotDeviceController {

	private final IIotDeviceService deviceService;
	private final IUmsUserService umsUserService;
	private final IPmsRoleService pmsRoleService;

	@GetMapping
	@Operation(summary = "设备管理")
	public Result<PageResult<IotDevice>> list(IotDeviceParam param) {
		PageParam<IotDevice, IotDeviceParam> page = new PageParam<>(param);
		page.setDefaultOrder("create_time desc");
		IPage<IotDevice> pa = deviceService.page(page, page.getWrapper());
		List<IotDevice> records = pa.getRecords();
		records.forEach(k->{
			if (ObjectUtil.isNotEmpty(k.getRoleId())){
				PmsRole role = pmsRoleService.getById(k.getRoleId());
				if (role!=null){
					k.setRoleName(role.getName());
				}
			}
		});
		PageResult<IotDevice> pageResult = new PageResult<>(pa.getRecords(), pa.getTotal());
		return Result.OK(pageResult);
	}

	/**
	 * 新增设备
	 */
	@PostMapping
	@Operation(summary = "新增设备")
	public Result<?> create(@RequestBody IotDevice device) {
		deviceService.save(device);
		return Result.OK("新增设备成功");
	}

	/**
	 * 修改设备
	 */
	@PutMapping()
	@Operation(summary = "修改设备")
	public Result<?> update(@RequestBody IotDevice device) {
		deviceService.updateById(device);
		return Result.OK("修改设备成功");
	}

	/**
	 * 删除设备
	 */
	@DeleteMapping("/{id}")
	@Operation(summary = "删除设备")
	public Result<?> delete(@PathVariable Long id) {
		IotDevice iotDevice = deviceService.getById(id);
		iotDevice.setUserId(null);
		iotDevice.setUserName(null);
		deviceService.updateById(iotDevice);
		return Result.OK("删除设备成功");
	}


}
